import React, {createContext, useContext, useState, useEffect, useRef} from 'react';
import {useNavigate} from 'react-router-dom';
import {useDispatch} from 'react-redux';
import {getUserInfoThunk} from '@/redux/thunks/user';

interface AuthContextType {
    isAuthenticated: boolean;
    login: (token: string) => void;
    logout: () => void;
}

const AuthContext = createContext<AuthContextType | null>(null);

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({children}) => {
    const [isAuthenticated, setIsAuthenticated] = useState(!!localStorage.getItem('token'));
    const isOne = useRef<boolean>(false)

    const navigator = useNavigate();

    const dispatch = useDispatch()

    const login = (token: string) => {
        console.log(login)
        localStorage.setItem('token', token);
        setIsAuthenticated(true);
    };

    const logout = () => {
        localStorage.removeItem('token');
        setIsAuthenticated(false);
    };


    useEffect(() => {
        if (isAuthenticated) {
            if (!isOne.current) {
                dispatch(getUserInfoThunk() as any)
                isOne.current = true
            }

        } else {
            navigator('/login')
        }

    }, [isAuthenticated, dispatch, navigator]);

    return (
        <AuthContext.Provider value={{isAuthenticated, login, logout}}>
            {children}
        </AuthContext.Provider>
    );
};

export const useAuth = () => {
    const context = useContext(AuthContext);
    if (!context) {
        throw new Error('useAuth must be used within an AuthProvider');
    }
    return context;
};
